package com.study.test.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import static com.study.test.utils.Const.*;

@Controller
@RequestMapping("/upload")
@PropertySource("classpath:/application.properties")
public class FileUploadController {
    @Value("${spring.servlet.multipart.location}")
    private String saveDir;

    @GetMapping("toUpload")
    public String toLogin() {
        return "/user/upload";
    }
@ResponseBody
    @PostMapping("/uploadFile")
    public String upload(@RequestParam("uploadFile") List<MultipartFile> uploadFire) {
        if (!CollectionUtils.isEmpty(uploadFire)) {
            for (MultipartFile file : uploadFire) {
                String originalFilename = file.getOriginalFilename();
                String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String newFilename = UUID.randomUUID() + suffix;

                File dir = new File(saveDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                try {
                    file.transferTo(new File(saveDir + newFilename));
                    return uploadFileSuccess;
                } catch (IOException e) {
                    e.printStackTrace();
                    return uploadFileError;
                }

            }

        }

        return noChooseFile;
    }
}



